﻿namespace Basic.Repository.SqlSugar
{
    public class BaseDBConfig
    {
        public static DBConfig dbConfig { get; set; }

        public static (List<MutiDBOperate> allDbs,
            List<MutiDBOperate> slaveDbs) MutiConnectionString => MutiInitConn();

        public static (List<MutiDBOperate>, List<MutiDBOperate>) MutiInitConn()
        {

            List<MutiDBOperate> listdatabase = dbConfig.DataBase
                .Where(i => i.Enabled).ToList();

            List<MutiDBOperate> listdatabaseSimpleDB = new List<MutiDBOperate>();//单库
            List<MutiDBOperate> listdatabaseSlaveDB = new List<MutiDBOperate>();//从库

            // 单库，且不开启读写分离，只保留一个
            if (!dbConfig.CQRSEnabled && !dbConfig.MutiDBEnabled)
            {
                if (listdatabase.Count == 1)
                {
                    return (listdatabase, listdatabaseSlaveDB);
                }
                else
                {
                    var dbFirst = listdatabase.FirstOrDefault(d => d.ConnId == dbConfig.MainDb);
                    if (dbFirst == null)
                    {
                        dbFirst = listdatabase.FirstOrDefault();
                    }
                    listdatabaseSimpleDB.Add(dbFirst);
                    return (listdatabaseSimpleDB, listdatabaseSlaveDB);
                }
            }


            // 读写分离，且必须是单库模式，获取从库

            if (dbConfig.CQRSEnabled && !dbConfig.MutiDBEnabled)
            {
                if (listdatabase.Count > 1)
                {
                    listdatabaseSlaveDB = listdatabase.Where(d => d.ConnId != dbConfig.MainDb.ToString()).ToList();
                }
            }
            return (listdatabase, listdatabaseSlaveDB);
            //}
        }

    }




    public static class MainDb
    {
        public static string CurrentDbConnId = "1";
    }
}